import BaseScene from './BaseScene';

export default class PerformanceTestScene extends BaseScene {
    constructor(game) {
        super(game);
        
        // 测试配置
        this.config = {
            renderingTest: {
                objectCount: 50,     // 减少对象数量，避免小游戏环境卡顿
                frames: 60,          // 调整为1秒的帧数
                objectSize: {        
                    min: 10,         // 减小对象尺寸
                    max: 30
                }
            },
            memoryTest: {
                objectCount: 500,    // 减少对象数量，适应小游戏内存限制
                arraySize: 50,       // 减小数组大小
                duration: 2000       // 增加测试时间到2秒
            },
            sceneTest: {
                interval: 800        // 增加场景切换间隔，确保转换完成
            }
        };

        this.testCases = [
            this.testResourceLoading.bind(this),
            this.testSceneTransitions.bind(this),
            this.testRenderingPerformance.bind(this),
            this.testMemoryUsage.bind(this)
        ];
        
        this.currentTest = 0;
        this.testResults = [];
        this.progress = 0;
    }

    async init() {
        console.log('开始性能测试...');
        await this.runTests();
    }

    async runTests() {
        for (let i = 0; i < this.testCases.length; i++) {
            try {
                this.currentTestName = `测试 ${i + 1}/${this.testCases.length}`;
                this.updateProgress(i / this.testCases.length);
                await this.testCases[i]();
            } catch (error) {
                console.error('测试执行失败:', error);
            }
        }
        
        this.updateProgress(1);
        this.currentTestName = '测试完成';
        this.showTestResults();
    }

    // 测试资源加载性能
    async testResourceLoading() {
        console.log('测试资源加载性能...');
        this.currentTestName = '资源加载测试';
        
        try {
            // 测试背景图片加载
            this.game.performanceMonitor.startResourceLoad('test_backgrounds');
            await this.game.loadBackgrounds();
            this.game.performanceMonitor.endResourceLoad('test_backgrounds');
            
            // 测试音频资源加载
            this.game.performanceMonitor.startResourceLoad('test_audio');
            await this.game.resourceManager.initSounds();
            this.game.performanceMonitor.endResourceLoad('test_audio');
            
            // 添加错误处理和超时机制
            const timeout = new Promise((_, reject) => {
                setTimeout(() => reject(new Error('资源加载超时')), 10000);
            });
            
            await Promise.race([
                this.game.resourceManager.preloadAll(),
                timeout
            ]);
            
        } catch (error) {
            console.error('资源加载测试失败:', error);
            // 记录错误但继续其他测试
        }
    }

    // 测试场景切换性能
    async testSceneTransitions() {
        console.log('测试场景切换性能...');
        
        const scenes = ['menu', 'lobby', 'game', 'result'];
        for (let i = 0; i < scenes.length - 1; i++) {
            await new Promise(resolve => setTimeout(resolve, 500));
            this.game.switchScene(scenes[i], scenes[i + 1]);
        }
    }

    // 测试渲染性能
    async testRenderingPerformance() {
        console.log('测试渲染性能...');
        this.currentTestName = '渲染性能测试';
        
        const { objectCount, frames, objectSize } = this.config.renderingTest;
        
        // 创建测试对象
        const testObjects = [];
        for (let i = 0; i < objectCount; i++) {
            testObjects.push({
                x: Math.random() * this.game.canvas.width,
                y: Math.random() * this.game.canvas.height,
                size: objectSize.min + Math.random() * (objectSize.max - objectSize.min),
                color: `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
            });
        }
        
        // 进行渲染测试
        for (let frame = 0; frame < frames; frame++) {
            this.updateProgress((frame + 1) / frames);
            this.renderTestObjects(testObjects);
            await new Promise(resolve => requestAnimationFrame(resolve));
        }
    }

    // 测试内存使用
    async testMemoryUsage() {
        console.log('测试内存使用...');
        this.currentTestName = '内存使用测试';
        
        const { objectCount, arraySize, duration } = this.config.memoryTest;
        
        // 创建测试对象
        const objects = [];
        for (let i = 0; i < objectCount; i++) {
            this.updateProgress(i / objectCount);
            objects.push({
                id: i,
                data: new Array(arraySize).fill(Math.random())
            });
        }
        
        // 等待指定时间
        await new Promise(resolve => setTimeout(resolve, duration));
        objects.length = 0;
    }

    // 渲染测试对象
    renderTestObjects(objects) {
        const ctx = this.game.ctx;
        ctx.clearRect(0, 0, this.game.canvas.width, this.game.canvas.height);
        
        objects.forEach(obj => {
            ctx.fillStyle = obj.color;
            ctx.beginPath();
            ctx.arc(obj.x, obj.y, obj.size, 0, Math.PI * 2);
            ctx.fill();
        });
    }

    // 显示测试结果
    showTestResults() {
        const report = this.game.getPerformanceReport();
        console.log('性能测试报告:', report);
        
        // 将结果保存到文件
        this.saveTestResults(report);
    }

    // 保存测试结果
    saveTestResults(report) {
        const results = {
            timestamp: new Date().toISOString(),
            deviceInfo: {
                platform: wx.getSystemInfoSync().platform,
                model: wx.getSystemInfoSync().model,
                system: wx.getSystemInfoSync().system,
                SDKVersion: wx.getSystemInfoSync().SDKVersion,
                benchmarkLevel: wx.getSystemInfoSync().benchmarkLevel,
                windowWidth: wx.getSystemInfoSync().windowWidth,
                windowHeight: wx.getSystemInfoSync().windowHeight
            },
            testConfig: this.config,
            performanceData: report
        };
        
        // 将结果写入文件
        const fileName = `performance_test_${Date.now()}.json`;
        const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
        
        try {
            wx.getFileSystemManager().writeFileSync(
                filePath,
                JSON.stringify(results, null, 2),
                'utf8'
            );
            
            console.log('测试结果已保存到:', filePath);
            
            // 显示测试完成提示
            wx.showToast({
                title: '测试完成',
                icon: 'success',
                duration: 2000
            });
        } catch (error) {
            console.error('保存测试结果失败:', error);
            wx.showToast({
                title: '保存失败',
                icon: 'error',
                duration: 2000
            });
        }
    }

    // 更新进度显示
    updateProgress(progress) {
        this.progress = progress;
        this.render(); // 触发重新渲染
    }

    // 渲染测试进度
    render() {
        const ctx = this.game.ctx;
        
        // 清空画布
        ctx.clearRect(0, 0, this.game.canvas.width, this.game.canvas.height);
        
        // 绘制标题
        ctx.fillStyle = '#333';
        ctx.font = 'bold 24px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('性能测试进行中...', this.game.canvas.width / 2, 100);
        
        // 绘制进度条背景
        ctx.fillStyle = '#eee';
        ctx.fillRect(100, 150, this.game.canvas.width - 200, 30);
        
        // 绘制进度条
        ctx.fillStyle = '#4CAF50';
        ctx.fillRect(100, 150, (this.game.canvas.width - 200) * this.progress, 30);
        
        // 绘制进度文本
        ctx.fillStyle = '#333';
        ctx.fillText(`${Math.round(this.progress * 100)}%`, this.game.canvas.width / 2, 170);
        
        // 如果有当前测试名称，显示它
        if (this.currentTestName) {
            ctx.fillText(this.currentTestName, this.game.canvas.width / 2, 220);
        }
    }
} 